package com.example.aiinterview.controller;

import com.example.aiinterview.model.*;
import com.example.aiinterview.service.AIService;
import com.example.aiinterview.service.InterviewService;
import com.example.aiinterview.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/chat")
@RequiredArgsConstructor
public class ChatController {

    private final InterviewService interviewService;
    private final UserService userService;
    private final AIService aiService;

    @PostMapping("/send")
    public ResponseEntity<Map<String, Object>> sendMessage(
            @RequestBody Map<String, Object> request,
            Authentication authentication) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 检查请求参数
            Object interviewIdObj = request.get("interviewId");
            Object messageObj = request.get("message");
            
            if (interviewIdObj == null) {
                response.put("success", false);
                response.put("error", "面试ID不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            if (messageObj == null) {
                response.put("success", false);
                response.put("error", "消息内容不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            Long interviewId = Long.valueOf(interviewIdObj.toString());
            String message = messageObj.toString().trim();
            
            if (message.isEmpty()) {
                response.put("success", false);
                response.put("error", "消息内容不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            User user = userService.findByUsername(authentication.getName());
            if (user == null) {
                response.put("success", false);
                response.put("error", "用户不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            Interview interview = interviewService.findById(interviewId);
            if (interview == null) {
                response.put("success", false);
                response.put("error", "面试不存在，ID: " + interviewId);
                return ResponseEntity.badRequest().body(response);
            }
            
            // 检查面试是否属于当前用户
            if (interview.getUser() == null || !interview.getUser().getId().equals(user.getId())) {
                response.put("success", false);
                response.put("error", "无权访问此面试");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 保存用户消息
            ChatMessage userMessage = new ChatMessage();
            userMessage.setInterview(interview);
            userMessage.setSender(ChatMessage.MessageSender.USER);
            userMessage.setContent(message);
            userMessage.setTimestamp(LocalDateTime.now());
            interview.addChatMessage(userMessage);
            
            // 生成AI回复
            String aiResponse = generateAIResponse(interview, message);
            
            // 更新问题编号（在生成AI回复后）
            if (interview.getCurrentQuestionNumber() < interview.getTotalQuestions()) {
                interview.setCurrentQuestionNumber(interview.getCurrentQuestionNumber() + 1);
            }
            
            // 保存AI消息
            ChatMessage aiMessage = new ChatMessage();
            aiMessage.setInterview(interview);
            aiMessage.setSender(ChatMessage.MessageSender.AI);
            aiMessage.setContent(aiResponse);
            aiMessage.setTimestamp(LocalDateTime.now());
            interview.addChatMessage(aiMessage);
            
            // 检查是否完成面试
            boolean interviewCompleted = checkInterviewCompletion(interview);
            if (interviewCompleted) {
                interview.setStatus(Interview.InterviewStatus.COMPLETED);
                interview.setEndTime(LocalDateTime.now());
                // 生成最终评估
                generateFinalEvaluation(interview);
            }
            
            interviewService.saveInterview(interview);
            
            response.put("success", true);
            response.put("aiResponse", aiResponse);
            response.put("interviewCompleted", interviewCompleted);
            
        } catch (Exception e) {
            System.err.println("发送消息时发生异常: " + e.getMessage());
            e.printStackTrace();
            response.put("success", false);
            response.put("error", "服务器内部错误，请稍后重试");
        }
        
        return ResponseEntity.ok(response);
    }
    
    @GetMapping("/history/{interviewId}")
    public ResponseEntity<Map<String, Object>> getChatHistory(
            @PathVariable Long interviewId,
            Authentication authentication) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            if (interviewId == null) {
                response.put("success", false);
                response.put("error", "面试ID不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            User user = userService.findByUsername(authentication.getName());
            if (user == null) {
                response.put("success", false);
                response.put("error", "用户不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            Interview interview = interviewService.findById(interviewId);
            if (interview == null) {
                response.put("success", false);
                response.put("error", "面试不存在，ID: " + interviewId);
                return ResponseEntity.badRequest().body(response);
            }
            
            // 检查面试是否属于当前用户
            if (interview.getUser() == null || !interview.getUser().getId().equals(user.getId())) {
                response.put("success", false);
                response.put("error", "无权访问此面试");
                return ResponseEntity.badRequest().body(response);
            }
            
            List<Map<String, Object>> messages = interview.getChatMessages().stream()
                    .sorted((m1, m2) -> m1.getTimestamp().compareTo(m2.getTimestamp()))
                    .map(msg -> {
                        Map<String, Object> msgMap = new HashMap<>();
                        msgMap.put("sender", msg.getSender().name().toLowerCase());
                        msgMap.put("content", msg.getContent());
                        msgMap.put("timestamp", msg.getTimestamp());
                        return msgMap;
                    })
                    .collect(Collectors.toList());
            
            response.put("success", true);
            response.put("messages", messages);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("error", e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    private String generateAIResponse(Interview interview, String userMessage) {
        try {
            // 检查参数
            if (interview == null) {
                return "抱歉，面试信息不存在，请重新开始面试。";
            }
            
            if (userMessage == null || userMessage.trim().isEmpty()) {
                return "请提供您的回答内容。";
            }
            
            // 构建上下文
            StringBuilder context = new StringBuilder();
            context.append("你是一个专业的面试官，正在对候选人进行面试。\n");
            context.append("职位：").append(interview.getJobPosition() != null ? interview.getJobPosition() : "未指定").append("\n");
            context.append("候选人简历概括：").append(interview.getResumeSummary() != null ? interview.getResumeSummary() : "无简历信息").append("\n");
            context.append("当前是第").append(interview.getCurrentQuestionNumber() != null ? interview.getCurrentQuestionNumber() : 1).append("个问题，总共").append(interview.getTotalQuestions() != null ? interview.getTotalQuestions() : 5).append("个问题。\n\n");
            
            // 添加聊天历史
            context.append("面试对话历史：\n");
            if (interview.getChatMessages() != null && !interview.getChatMessages().isEmpty()) {
                List<ChatMessage> recentMessages = interview.getChatMessages().stream()
                        .filter(msg -> msg != null && msg.getContent() != null)
                        .sorted((m1, m2) -> {
                            if (m1.getTimestamp() == null || m2.getTimestamp() == null) {
                                return 0;
                            }
                            return m2.getTimestamp().compareTo(m1.getTimestamp());
                        })
                        .limit(10)
                        .collect(Collectors.toList());
                
                for (ChatMessage msg : recentMessages) {
                    String sender = msg.getSender() == ChatMessage.MessageSender.USER ? "候选人" : "面试官";
                    String content = msg.getContent() != null ? msg.getContent() : "";
                    context.append(sender).append("：").append(content).append("\n");
                }
            } else {
                context.append("暂无对话历史\n");
            }
            
            context.append("\n候选人刚才的回答：").append(userMessage).append("\n");
            
            if (interview.getCurrentQuestionNumber() == 1) {
                // 第一个问题，开始面试
                context.append("请根据简历内容，提出第一个面试问题。问题应该与职位相关，能够评估候选人的专业技能和经验。");
            } else if (interview.getCurrentQuestionNumber() < interview.getTotalQuestions()) {
                // 中间问题
                context.append("请根据候选人的回答，提出下一个面试问题。问题应该深入评估候选人的能力，可以是技术问题、行为问题或情景问题。");
            } else {
                // 最后一个问题
                context.append("这是最后一个问题。请根据候选人的回答，提出一个总结性的问题，然后结束面试。");
            }
            
            String aiResponse = aiService.generateResponse(context.toString());
            
            return aiResponse;
            
        } catch (Exception e) {
            return "抱歉，我遇到了一些技术问题。请稍后重试。";
        }
    }
    
    private boolean checkInterviewCompletion(Interview interview) {
        if (interview == null) {
            return false;
        }
        
        Integer currentQuestion = interview.getCurrentQuestionNumber();
        Integer totalQuestions = interview.getTotalQuestions();
        
        if (currentQuestion == null || totalQuestions == null) {
            return false;
        }
        
        return currentQuestion >= totalQuestions;
    }
    
    private void generateFinalEvaluation(Interview interview) {
        try {
            if (interview == null) {
                return;
            }
            
            StringBuilder context = new StringBuilder();
            context.append("你是一名专业的HR，请对这次面试进行全面的最终评估。\n\n");
            context.append("面试基本信息：\n");
            context.append("- 目标职位：").append(interview.getJobPosition() != null ? interview.getJobPosition() : "未指定").append("\n");
            context.append("- 候选人简历概况：").append(interview.getResumeSummary() != null ? interview.getResumeSummary() : "无简历信息").append("\n\n");
            
            context.append("面试对话记录：\n");
            if (interview.getChatMessages() != null && !interview.getChatMessages().isEmpty()) {
                for (ChatMessage msg : interview.getChatMessages()) {
                    if (msg != null && msg.getContent() != null) {
                        String sender = msg.getSender() == ChatMessage.MessageSender.USER ? "候选人" : "面试官";
                        context.append(sender).append("：").append(msg.getContent()).append("\n");
                    }
                }
            } else {
                context.append("无对话记录\n");
            }
            
            context.append("\n请提供以下内容的专业评估报告：\n");
            context.append("1. 总体评分（1-10分，请明确给出具体分数）\n");
            context.append("2. 主要优势（至少3个具体优点）\n");
            context.append("3. 需要改进的地方（至少3个具体建议）\n");
            context.append("4. 技能匹配度分析\n");
            context.append("5. 是否推荐录用及理由\n");
            context.append("6. 具体的职业发展建议\n");
            context.append("7. 薪资建议（如果适用）\n\n");
            context.append("请用专业、客观的语言进行评估，确保评估结果对候选人具有指导意义。");
            
            String evaluation = aiService.generateResponse(context.toString());
            
            // 提取评分
            Double score = extractScore(evaluation);
            
            interview.setFinalScore(score);
            interview.setFeedback(evaluation);
            
            System.out.println("✅ 面试评估完成，评分: " + score);
            
        } catch (Exception e) {
            System.err.println("❌ 面试评估失败: " + e.getMessage());
            e.printStackTrace();
            interview.setFinalScore(5.0);
            interview.setFeedback("面试评估过程中出现技术问题，请联系管理员。");
        }
    }
    
    private Double extractScore(String evaluation) {
        try {
            if (evaluation == null || evaluation.trim().isEmpty()) {
                return 5.0;
            }
            
            // 更精确的评分提取逻辑
            String[] lines = evaluation.split("\n");
            for (String line : lines) {
                line = line.trim();
                
                // 查找包含评分的行
                if (line.contains("评分") || line.contains("分数") || line.contains("得分")) {
                    // 提取数字
                    String[] words = line.split("\\s+");
                    for (String word : words) {
                        try {
                            // 尝试提取数字
                            if (word.matches("\\d+(\\.\\d+)?")) {
                                double score = Double.parseDouble(word);
                                if (score >= 1.0 && score <= 10.0) {
                                    return score;
                                }
                            }
                            // 处理分数格式如 "8/10"
                            if (word.matches("\\d+/10")) {
                                String[] parts = word.split("/");
                                double score = Double.parseDouble(parts[0]);
                                if (score >= 1.0 && score <= 10.0) {
                                    return score;
                                }
                            }
                        } catch (NumberFormatException ignored) {
                            // 继续尝试下一个词
                        }
                    }
                }
            }
            
            // 如果没找到具体分数，尝试从整个文本中提取
            if (evaluation.contains("10分") || evaluation.contains("10/10") || evaluation.contains("10.0")) return 10.0;
            if (evaluation.contains("9分") || evaluation.contains("9/10") || evaluation.contains("9.0")) return 9.0;
            if (evaluation.contains("8分") || evaluation.contains("8/10") || evaluation.contains("8.0")) return 8.0;
            if (evaluation.contains("7分") || evaluation.contains("7/10") || evaluation.contains("7.0")) return 7.0;
            if (evaluation.contains("6分") || evaluation.contains("6/10") || evaluation.contains("6.0")) return 6.0;
            if (evaluation.contains("5分") || evaluation.contains("5/10") || evaluation.contains("5.0")) return 5.0;
            if (evaluation.contains("4分") || evaluation.contains("4/10") || evaluation.contains("4.0")) return 4.0;
            if (evaluation.contains("3分") || evaluation.contains("3/10") || evaluation.contains("3.0")) return 3.0;
            if (evaluation.contains("2分") || evaluation.contains("2/10") || evaluation.contains("2.0")) return 2.0;
            if (evaluation.contains("1分") || evaluation.contains("1/10") || evaluation.contains("1.0")) return 1.0;
            
            // 默认评分
            return 6.0;
        } catch (Exception e) {
            System.err.println("Error extracting score: " + e.getMessage());
            return 5.0;
        }
    }
}
